/**
 * Description
 *
 * Creation Date 02/11/2017
 * @author Candy
 */
'use strict';
import BannerModel from '../models/banners';
import cheerio from 'cheerio'
import superagent from 'superagent'

class Banner {
	constructor() {}
	async getBanner(req, res, next) {
		superagent.get('https://www.smartbuyglasses.cn/')
			.end(async(err, ares) => {
				if (err) {
					console.log(err);
					return;
				}
				try {
					const $ = cheerio.load(ares.text);
					let banner_link ='',
						id = 0,
						banner_image = '';
					let elements = $('#slideshow .main_image li');
					for (let i = 0; i<elements.length; i++) {
						banner_link = $(elements[i]).find('a').attr('href');
						banner_image = $(elements[i]).find('img').attr('src');
						const hadbannerInfo = await BannerModel.findOne({banner_link, banner_image}, '-_id');
						if(!hadbannerInfo) {
							id += 1;
							await BannerModel.create({banner_id: id, banner_link, banner_image})
						}
					}
					const bannerData = await BannerModel.find({}, '-_id');
					res.send({
						status: 1,
						data: bannerData
					})
				} catch (err) {
					console.log('Error', err)
					throw new Error(err)
				}
			});
	}
}

export default new Banner()

